import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Message, User } from '../types'
import { DEFAULT_AVATAR } from '../constants/default'

export const useChatStore = defineStore('chat', () => {
  // 头像样式列表
  const avatarStyles = [
    'avataaars',
    'bottts',
    'pixel-art',
    'adventurer',
    'big-ears',
    'micah'
  ]

  // 随机获取头像样式
  const getRandomAvatarStyle = () => {
    return avatarStyles[Math.floor(Math.random() * avatarStyles.length)]
  }

  // 生成头像URL
  const generateAvatarUrl = (seed: string, style?: string) => {
    try {
      return `https://api.dicebear.com/7.x/${style || getRandomAvatarStyle()}/svg?seed=${seed}`
    } catch (error) {
      // 如果生成失败，返回默认头像
      return seed.includes('bot') ? DEFAULT_AVATAR.BOT : DEFAULT_AVATAR.USER
    }
  }

  const messages = ref<Message[]>([])
  const currentUser = ref<User>({
    id: '1',
    name: '我',
    avatar: generateAvatarUrl('user1', 'avataaars')
  })

  const otherUser: User = {
    id: '2',
    name: '小助手',
    avatar: generateAvatarUrl('bot1', 'bottts')
  }

  // 模拟回复消息
  const simulateReply = (content: string) => {
    // 模拟延迟 1-2 秒回复
    const delay = Math.random() * 1000 + 1000
    setTimeout(() => {
      const replies = [
        "这很有趣呢！",
        "能详细说说吗？",
        "我明白你的意思了",
        "谢谢你的分享！",
        "你觉得怎么样呢？",
        "确实是这样呢",
        "我也是这么想的"
      ]
      
      const message: Message = {
        id: Date.now().toString(),
        content: replies[Math.floor(Math.random() * replies.length)],
        sender: otherUser.id,
        timestamp: Date.now()
      }
      messages.value.push(message)
    }, delay)
  }

  const addMessage = (content: string) => {
    const message: Message = {
      id: Date.now().toString(),
      content,
      sender: currentUser.value.id,
      timestamp: Date.now()
    }
    messages.value.push(message)
    
    // 触发模拟回复
    simulateReply(content)
  }

  // 初始化一些测试消息
  messages.value = [
    {
      id: '1',
      content: '你好！',
      sender: otherUser.id,
      timestamp: Date.now() - 1000000
    },
    {
      id: '2',
      content: '你好啊！',
      sender: currentUser.value.id,
      timestamp: Date.now() - 500000
    }
  ]

  // 更新用户头像
  const updateUserAvatar = (avatarUrl: string) => {
    currentUser.value.avatar = avatarUrl
  }

  return {
    messages,
    currentUser,
    addMessage,
    updateUserAvatar
  }
}) 